package com.app.art.utils;

import com.atom.module.common.utils.spring.SpringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class QiNiuOssUtil {

    // AccessKey nIkBBCIqsmAAkt3r1xB2DdZKmoI2HnfDyFBXxobB
    // SecretKey  kJAuprKvdDnc_MdwuRserebeeqQDRIYrvL9keV04

    private String accessKey;
    private String secretKey;
    private String bucketName;
    private UploadManager uploadManager;

    public QiNiuOssUtil(String accessKey, String secretKey, String bucketName) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = Configuration.create(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        this.uploadManager = new UploadManager(new Configuration());


    }

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) throws QiniuException, JsonProcessingException {
        // 创建OSSClient实例。
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketName);
        Response response = uploadManager.put(bytes, objectName, upToken);
        //解析上传成功的结果
        ObjectMapper bean = SpringUtils.getBean(ObjectMapper.class);
        DefaultPutRet putRet = bean.readValue(response.bodyString(), DefaultPutRet.class);
        // domain   下载 domain, eg: qiniu.com【必须】
        // useHttps 是否使用 https【必须】
        // key      下载资源在七牛云存储的 key【必须】
        DownloadUrl url = new DownloadUrl("t2pvqm5dv.hn-bkt.clouddn.com", false, putRet.key);
        // 带有效期
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        long deadline = System.currentTimeMillis() / 1000 + expireInSeconds;
        return url.buildURL(auth, deadline);
    }
}
// http://t2pvqm5dv.hn-bkt.clouddn.com/f9184bcc-1ba2-4777-a3b9-5c7efa685292wyz.txt?e=1758092643&token=nIkBBCIqsmAAkt3r1xB2DdZKmoI2HnfDyFBXxobB:F_uqfHEIOBXPem5QerpeXZ_-Er8=

// https://t2pvqm5dv.hn-bkt.clouddn.com/f9184bcc-1ba2-4777-a3b9-5c7efa685292wyz.txt?e=1758095920&token=nIkBBCIqsmAAkt3r1xB2DdZKmoI2HnfDyFBXxobB:H0MyT7g2SD84FO34iabyMP3eRw8=